#include "TestMouseJoint.h"
#include "Tools.h"

CCScene* TestMouseJoint::scene()
{
	CCScene* sc = CCScene::create();
	TestMouseJoint* layer = TestMouseJoint::create();
	sc->addChild(layer);

	return sc;
}

bool TestMouseJoint::init()
{
	BaseLayer::init();

	initBody();

	setTouchEnabled(true);
	setTouchMode(kCCTouchesOneByOne);
	scheduleUpdate();

	return true;
}

void TestMouseJoint::initBody()
{
	b2BodyDef bodyDef;
	bodyDef.type = b2_dynamicBody;
	b2Vec2 vec = Tools::convertTob2WorldSpace(ccp(winSize.width / 2, winSize.height / 2));
	bodyDef.position.Set(vec.x, vec.y);
	
	b2PolygonShape shape1;
	shape1.SetAsBox(2.0f, 2.0f);

	b2FixtureDef fixtureDef;
	fixtureDef.density = 1.0f;
	fixtureDef.friction = 0.3f;
	fixtureDef.restitution = 1.0f;
	
	fixtureDef.shape = &shape1;
	b2Body* bodyA = m_world->CreateBody(&bodyDef);
	bodyA->CreateFixture(&fixtureDef);

	b2CircleShape shape2;
	shape2.m_radius = 2.0f;

	fixtureDef.shape = &shape2;
	b2Body* bodyB = m_world->CreateBody(&bodyDef);
	bodyB->CreateFixture(&fixtureDef);
}

void TestMouseJoint::update(float dt)
{
	m_world->Step(dt, 8, 1);
}

bool TestMouseJoint::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
	const CCPoint ptTouch = pTouch->getLocation();
	const b2Vec2 bodyVec = Tools::convertTob2WorldSpace(ptTouch);

	for (b2Body* b = m_world->GetBodyList(); b; b = b->GetNext()) {
		for (b2Fixture* fix = b->GetFixtureList(); fix; fix = fix->GetNext()) {
			if (fix->TestPoint(bodyVec)) {
				b2MouseJointDef jointDef;
				jointDef.bodyA = m_groundBody;
				jointDef.bodyB = b;
				jointDef.maxForce = 1000 * b->GetMass();
				jointDef.target = bodyVec;
				b->SetAwake(true);
				m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&jointDef);
				
				CCLOG("=========Create mouse joint==========");

				return true;
			}
		}
	}

	return false;
}

void TestMouseJoint::ccTouchMoved(CCTouch *pTouch, CCEvent *pEvent)
{
	if (!m_mouseJoint) return;

	b2Vec2 mouseVec(Tools::convertTob2WorldSpace(pTouch->getLocation()));
	m_mouseJoint->SetTarget(mouseVec);
}

void TestMouseJoint::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
	if (m_mouseJoint) {
		m_world->DestroyJoint(m_mouseJoint);
		m_mouseJoint = NULL;
		
		CCLOG("=========Delete mouse joint==========");
	}
}